import 'package:peach/entity/_.dart';
import 'package:peach/db/SQLite.dart';

class LikeService {

  static String TableName = "Like";
  static String tabsNameSingleGraph = "SingleGraph";

  ///====================== 写真收藏 ======================///

  /// 添加喜欢
  static Future<int> addLike(LikeEntity user) async {
    var _db = await SQLite().db;
    return await _db.insert(LikeService.TableName, user.toJson());
  }

  /// 查询所有喜欢数据
  static Future<List<LikeEntity>> findAll() async {
    var _db = await await SQLite().db;
    List<Map<String, dynamic>> result = await _db.query(LikeService.TableName);

    return result.isNotEmpty
        ? result.map((e) {
            return LikeEntity.fromJson(e);
          }).toList()
        :[];
  }

  /// 根据id查询数据，注意这里返回 true，false，
  /// 主要为了在详情页控制收藏按钮的样式，如果需要返回数据
  /// 需要修改类型为： Future<List<LikeEntity>> 和 return的结果
  /// LikeEntity.fromJson(e);
  static Future<bool> find(int id) async {
    var _db = await SQLite().db;
    List<Map<String, dynamic>> result = await _db.query(
        LikeService.TableName,
        where: 'id = ?',
        whereArgs: [id]
    );
    return result.isNotEmpty ? true : false;
  }

  /// 根据id删除数据
  static Future<int> delete(int id) async {
    var _db = await await SQLite().db;
    return await _db.delete(
        LikeService.TableName,
        where: 'id = ?',
        whereArgs: [id]
    );
  }

  ///====================== 单图收藏 ======================

  // 查询所有收藏的图片
  static Future<List<SingleGraphEntity>> findAllImg() async {
    var _db = await await SQLite().db;
    List<Map<String, dynamic>> result = await _db.query(LikeService.tabsNameSingleGraph, orderBy: "id DESC");
    return result.isNotEmpty
        ? result.map((e) {
            return SingleGraphEntity.fromJson(e);
          }).toList()
        :[];
  }

  // 添加图片
  static Future<int> addImg(SingleGraphEntity Img) async {
    var _db = await SQLite().db;
    return await _db.insert(LikeService.tabsNameSingleGraph, Img.toJson());
  }

  // 检测图片是否已经收藏过
  static Future<bool> checkIsLike(String src) async {
    var _db = await SQLite().db;
    List<Map<String, dynamic>> result = await _db.query(
        LikeService.tabsNameSingleGraph,
        where: 'src = ?',
        whereArgs: [src]
    );
    return result.isNotEmpty ? true : false;
  }

  // 根据 地址删除收藏的图片
  static Future<int> deleteImg(String src) async {
    var _db = await await SQLite().db;
    return await _db.delete(
        LikeService.tabsNameSingleGraph,
        where: 'src = ?',
        whereArgs: [src]
    );
  }

}
